package com.github.baichuan.application.scaffold.rest.domain.identity;

import com.github.baichuan.application.scaffold.rest.domain.application.Application;
import com.github.baichuan.application.scaffold.rest.domain.authorization.Role;
import com.github.baichuan.application.scaffold.rest.domain.organization.Org;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Entity
@Getter
@Setter
public class ApplicationMember {
    @Id
    private String id;

    @ManyToOne
    @JoinColumn(name = "member_id")
    private Member member;

    @ManyToOne
    @JoinColumn(name = "application_id")
    private Application application;

    @ManyToOne
    @JoinColumn(name = "org_uid")
    private Org org;

    private String memberType;

    private LocalDate expire;

    private int loginCount;

    private LocalDateTime createTime;

    @ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(name = "application_member_privilege", joinColumns = @JoinColumn(name = "application_member_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private List<Role> roles;

    public static ApplicationMember newInstance(@NonNull Application application, @NonNull Member member, @NonNull String id){
        ApplicationMember applicationMember = new ApplicationMember();
        applicationMember.setId(id);
        applicationMember.application = application;
        applicationMember.member = member;
        applicationMember.createTime = LocalDateTime.now();
        return applicationMember;
    }

    public boolean isAdmin(){
        return memberType.equals("ADMIN");
    }
}
